package com.minisoft.call;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.crypto.digest.MD5;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import lombok.Data;

import com.alibaba.fastjson.JSONObject;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;

public class CallService {
    private static  String APP_KEY = "4c3b7d08b7365ee582e2fadab9c4d966";
    private static  String APP_SECRET = "bae5be1a7a3fb880c82ab0cff06a8666";
    private static  String AES_KEY = "yaKmeUTD6dhmxYITDzxBfg==";
    private static  String APP_ID = "wx01f0b018d4951666";
    private static String URL = "https://call-test.vuelma.com/yq-call/open/v2/pushCustomer";
    private static  int BATCH_SIZE = 2000; // 每批处理的最大数量
    private static  String OUT_PROJECT_ID = "1186667201753088666";

    //测试的标识
    private static  boolean isProduct = true;

    /** 4.18 2200
     * 1000013 0-200  200-2200/500
     * 1000014 0-200  200-2200/500
     * 1000004 0-200  200-2200/500
     * 1000016 0-200  200-2200/500
     * 1000009 0-200  200-2200/500
     * 4.21 2500
     * 1000013 2200-4700/500
     * 1000014 2200-4700/500
     * 1000004 2200-4700/500
     * 1000016 2200-4700/500【1150】【只收到第一批500】
     * 1000009 2200-4700/500【800】【收没收到】
     *
     * 5.09 2100
     * 1000004 4700-6800/500
     * 1000009 2200-4700/500【800】 重推
     * 1000016 2700-4700/500【650】 重推
     *
     * 5.22
     * 1000013 4700-25000/2000 【20300】
     * 1000014 4700-20000/2000 【15300】
     */
    public static void main(String[] args) {
//        String[] projectIds = new String[]{"1000013", "1000014", "1000004", "1000016", "1000009"};
//        String[] projectIds = new String[]{ "1000016"};
        String[] projectIds = new String[]{"1000013"};
        for (String projectId : projectIds) {
            doPush(projectId);
        }
    }

    private static void doPush(String projectId) {
        try {
            String excelPath = "D:/temp/aicallUser.xlsx"; // 请替换为实际的Excel文件路径
            if(isProduct){
                APP_KEY = "e8839909a1484ff79f44aa4b9f74fdf9";
                APP_SECRET = "1J2z-vzjffE1qyvO1Y6tNRkp4iZJ5J79";
                AES_KEY = "yaKmeUTD6dhmxYITDzxBfg==";
                APP_ID = "hfo0_fmxcgdwdxsxkl3acz";
                URL = "https://call.vuelma.com/yq-call/open/v2/pushCustomer";
                OUT_PROJECT_ID = projectId;
                excelPath = String.format("D:/AI call客/data-%s.xlsx", OUT_PROJECT_ID); // 请替换为实际的Excel文件路径
            }
            List<Customer> customers = readExcel(excelPath);
            customers = customers.subList(18700, NumberUtil.min(25000,customers.size()));
            System.out.println("推送总数：" + customers.size());
            batchPushCustomers(customers);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static List<Customer> readExcel(String filePath) throws Exception {
        List<Customer> customers = new ArrayList<>();
        ExcelReader reader = ExcelUtil.getReader(filePath);
        List<List<Object>> readAll = reader.read(1); // 从第二行开始读取，跳过表头

        for (List<Object> row : readAll) {
            Customer customer = new Customer();
            customer.setOutProjectId(String.valueOf(row.get(0)));
            customer.setProjectName(String.valueOf(row.get(1)));
            String phone = String.valueOf(row.get(2));
            customer.setPhone(encrypt(phone, AES_KEY));
            customer.setUserChannel(String.valueOf(row.get(3)));
            customers.add(customer);
        }

        reader.close();
        return customers;
    }

    private static void batchPushCustomers(List<Customer> customers) {
        int totalSize = customers.size();
        int batchCount = (totalSize + BATCH_SIZE - 1) / BATCH_SIZE; // 计算需要分几批

        for (int i = 0; i < batchCount; i++) {
            int fromIndex = i * BATCH_SIZE;
            int toIndex = Math.min((i + 1) * BATCH_SIZE, totalSize);
            List<Customer> batchCustomers = customers.subList(fromIndex, toIndex);
            
            System.out.println("正在处理第 " + (i + 1) + " 批数据，共 " + batchCustomers.size() + " 条记录");
            pushCustomers(batchCustomers);
            
            // 如果不是最后一批，等待1秒再处理下一批
            if (i < batchCount - 1) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private static void pushCustomers(List<Customer> customers) {
        JSONObject requestBody = new JSONObject();
        requestBody.put("outProjectId", OUT_PROJECT_ID);
        requestBody.put("outTaskId", IdUtil.fastSimpleUUID());
        requestBody.put("customers", customers);

        String timestamp = String.valueOf(System.currentTimeMillis());
        String nonce = RandomUtil.randomString("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ", 10);
        String sign = generateSign(timestamp, nonce);

        HttpResponse response = HttpRequest.post(URL)
                .header("appId", APP_ID)
                .header("timestamp", timestamp)
                .header("nonce", nonce)
                .header("sign", sign)
                .body(requestBody.toJSONString())
                .execute();

        System.out.println("Response: " + response.body());
    }

    private static String generateSign(String timestamp, String nonce) {
        String signStr = "appKey@" + APP_KEY + ":timestamp@" + timestamp + ":nonce@" + nonce + APP_SECRET;
        return MD5.create().digestHex(signStr);
    }

    private static String encrypt(String phone, String aesKey) throws Exception {
        byte[] decodedKey = Base64.getDecoder().decode(aesKey);
        SecretKeySpec key = new SecretKeySpec(decodedKey, 0, decodedKey.length, "AES");
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.ENCRYPT_MODE, key);
        byte[] encryptedBytes = cipher.doFinal(phone.getBytes());
        return Base64.getEncoder().encodeToString(encryptedBytes);
    }

    @Data
    static class Customer {
        private String outProjectId;
        private String projectName;
        private String phone;
        private String userChannel;
    }
} 